import React, { useState, useMemo } from 'react';
import styles from './index.less';
import { Row, Col, Radio, Tooltip, Table, Typography, Upload, message, Drawer, Card, Empty, Popconfirm } from 'antd';
import { PlusOutlined, SwapOutlined, EditFilled, CopyFilled, DeleteFilled } from '@ant-design/icons'
import IconFont from '@/components/IconFont';
import SortContent from './sortcontent'
import { useModel, history } from 'umi'
import { Tabs } from 'antd';
import { Scrollbars } from 'react-custom-scrollbars';
import DrawInitForm from '@/components/DrawInitForm';
import { postFetch, getFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import { useEffect } from 'react';

const { TabPane } = Tabs;

let col = { xs: 12, sm: 12, md: 8, lg: 6, xl: 4, xxl: 4 },
    cols = { xs: 24, sm: 24, md: 17, lg: 18, xl: 18, xxl: 18 };

const defaultlist = [
], typelister = {
    cpu: "电脑",
    phone: "手机",
    A4: "A4",
    other: "其他"
}


function Mytemplate() {
    const [list, setlist] = useState(defaultlist);
    const [activeKey, setactiveKey] = useState(["1"]);
    const { initialState, setInitialState } = useModel("@@initialState");
    const [destroy, setdestroy] = useState(false);
    const [drawerprops, setdrawerprops] = useState({
        title: "模板排序",
        placement: "right",
        visible: false,
        closable: false
    });

    const { data, error, loading, refresh } = useRequest(() => getFetch({ url: "/api/template", params: { is_all: 1 } }));

    useEffect(() => {
        getFetch({ url: "/api/data_group", params: { is_all: 1 } }).then(res => {
            let alllist = res?.data?.dataList ?? [];
            setlist(() => {
                return alllist.map(it => ({
                    tab: it.name,
                    key: it.id
                }))
            })
        })
    }, [])

    let alllist = useMemo(() => {
        return data?.data?.dataList ?? []
    }, [data]);



    const action = useRequest(postFetch, {
        manual: true,
        formatResult: (res) => res,
        debounceWait: 200,
        onSuccess: (result, params) => {

            if (result.code == 0) {
                message.success("操作成功");
                setdrawerprops(s => ({ ...s, visible: false }));
                refresh();
            } else {

            }
        }
    })


    let adddom = (placement) => (<div
        className='diybtn'
        onClick={async () => {
            await setdestroy(false);
            setdrawerprops(s => {
                return {
                    ...s,
                    val: "addon",
                    visible: true,
                    title: "新建模板",
                    placement: placement ?? "left",
                    width: 450,
                    fields: {
                        "name": {
                            "value": null,
                            "type": "input",
                            "title": "模板名称",
                            "name": [
                                "name"
                            ],
                            "required": true
                        },
                        "data_group_id": {
                            "value": null,
                            "type": "checktable",
                            "title": "选择数据组",
                            "name": [
                                "data_group_id"
                            ],
                            "required": true,
                            "columns": [
                                {
                                    "title": "数据组",
                                    "dataIndex": "name",
                                    "key": "name",
                                },
                                {
                                    "title": "编号",
                                    "dataIndex": "data_group_number",
                                    "key": "data_group_number",
                                    "search": false
                                }
                            ],
                            "editable": false,
                            "path": "/api/data_group",
                            "extraparams": { is_all: 1 },
                            "rowKey": "id",
                            "rowName": "name",
                            "tabletype": "radio"
                        },
                        "size": {
                            "value": null,
                            "type": "size",
                            "title": "模板展示尺寸",
                            "name": [
                                "size"
                            ],
                            "required": true
                        },
                    }
                }
            })
        }}
        style={{ backgroundColor: "#0cb83f" }}
    >
        <PlusOutlined style={{ marginRight: 6 }}></PlusOutlined>
        <span>创建新模版</span>
    </div>)


    return (<div>
        {
            !destroy && <DrawInitForm
                {...drawerprops}
                onClose={() => {
                    setdrawerprops({
                        ...drawerprops,
                        visible: false
                    })
                }}
                col={{ span: 24 }}
                submitData={(values) => {
                    if (drawerprops.val == "addon") {
                        values.data_group_id = values.data_group_id ? values.data_group_id[0] : drawerprops?.id ? drawerprops?.id : '';
                        action.run({ url: "/api/template", params: { ...values } });
                    } else if (drawerprops.val == "editon") {
                        values.data_group_id = values.data_group_id ? values.data_group_id[0] : '';
                        action.run({ url: "/api/template/" + drawerprops.id, params: { ...values }, method: "PUT" });
                    } else if (drawerprops.val == "copy") {
                        let data_group_id = values.data_group_id ? values.data_group_id[0] : '';
                        action.run({ url: "/api/template/copy_template", params: { id: drawerprops.id, data_group_id } })
                    }
                }}
                afterVisibleChange={(visible) => {
                    if (!visible) {
                        setdestroy(true);
                    }
                }}
            >
                {
                    drawerprops.val == "sort" && <div style={{ width: "100%", overflowX: "hidden", height: "100%" }}>
                        <Scrollbars
                            thumbMinSize={10}
                            autoHide
                            style={{ width: '100%', height: "100%", overflowX: "hidden" }}
                            hideTracksWhenNotNeeded={true}
                        >
                            <SortContent items={list} setItems={setlist} />
                        </Scrollbars>
                    </div>
                }
            </DrawInitForm>
        }

        <div className="fixedheader databg" style={{ transition: "all 0.4s", top: initialState.showaction ? 48 : 0 }}>
            <div className="container" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", height: "100%" }}>
                <div style={{ color: "#fff", fontWeight: "bolder" }}>
                    说明:任意一个模板必须基于相应的数据组来构建，在复制为新模板之后需要重新指定新模板对应的数据组，并构建新的数据链接关系。
                </div>
                {
                    adddom("right")
                }

            </div>

        </div>

        <div className='imgbg' style={{ backgroundImage: `url(${require("@/assets/mytempbg.jpg")})`, height: 300 }}>
            <div className="container" style={{ display: "flex", height: "100%" }}>
                <div className={styles.left}>
                    <h2>模板编辑说明</h2>
                    <p>
                        任意一个模板必须基于相应的数据组来构建，在复制为新模板之后需要重新指定新模板对应的数据组，<br />
                        并构建新的数据链接关系。
                    </p>
                    {
                        adddom()
                    }
                </div>
                <div className={styles.right}>
                    <img src={require("@/assets/ed.png")} alt="" />
                    <img src={require("@/assets/ed_1.png")} alt="" />
                </div>
            </div>
        </div>

        <div className="container card-container" style={{ padding: "32px 0 12px 0" }}>
            <Tabs
                type="card"
                defaultActiveKey="1"
                animated={true}
                onChange={() => {

                }}
                tabBarExtraContent={<a style={{ paddingRight: 12, color: "red" }}
                    onClick={async () => {
                        await setdestroy(false);
                        setdrawerprops(s => {
                            return {
                                ...s,
                                val: "sort",
                                visible: true,
                                title: "排序",
                                placement: "right",
                            }
                        })
                    }}
                >
                    <SwapOutlined rotate={90} style={{ paddingRight: 4 }} />
                    排序
                </a>}
            >
                {
                    list.map((it, index) => <TabPane key={index} {...it}>
                        <Row style={{ width: "100%", paddingLeft: 12, paddingTop: 12 }} gutter={12}>
                            <Col {...col}>
                                <Card
                                    hoverable
                                    style={{ width: "100%", height: 190, borderColor: "rgb(12, 184, 63,0.4)" }}
                                    onClick={async () => {
                                        await setdestroy(false);
                                        setdrawerprops(s => {
                                            return {
                                                ...s,
                                                val: "addon",
                                                visible: true,
                                                title: "新建模板",
                                                placement: "left",
                                                width: 450,
                                                id: it.key,
                                                fields: {
                                                    "name": {
                                                        "value": null,
                                                        "type": "input",
                                                        "title": "模板名称",
                                                        "name": [
                                                            "name"
                                                        ],
                                                        "required": true
                                                    },
                                                    "size": {
                                                        "value": null,
                                                        "type": "size",
                                                        "title": "模板展示尺寸",
                                                        "name": [
                                                            "size"
                                                        ],
                                                        "required": true
                                                    },
                                                }
                                            }
                                        })
                                    }}
                                >
                                    <div className='center' style={{ height: 190, flexDirection: "column", color: "rgb(12, 184, 63)" }}>
                                        <PlusOutlined style={{ fontSize: 24, fontWeight: "lighter", marginBottom: 12 }} />
                                        <span>
                                            新增模板
                                        </span>
                                    </div>
                                </Card>
                            </Col>
                            {
                                alllist.filter(item => item.data_group_id == it.key).map((item, i) => {
                                    return <Col {...col}>
                                        <Card
                                            hoverable
                                            key={i}
                                            style={{ flex: 1, height: 190, margin: "0 0 12px 0" }}
                                            actions={[
                                                <Tooltip title="编辑">
                                                    <EditFilled key="edit" onClick={async () => {
                                                        await setdestroy(false);
                                                        setdrawerprops(s => {
                                                            return {
                                                                ...s,
                                                                val: "editon",
                                                                visible: true,
                                                                title: "编辑模板",
                                                                placement: "left",
                                                                width: 450,
                                                                id: item.id,
                                                                fields: {
                                                                    "name": {
                                                                        "value": item.name,
                                                                        "type": "input",
                                                                        "title": "模板名称",
                                                                        "name": [
                                                                            "name"
                                                                        ],
                                                                        "required": true
                                                                    },
                                                                    "data_group_id": {
                                                                        "value": [item.data_group_id],
                                                                        "type": "checktable",
                                                                        "title": "选择数据组",
                                                                        "name": [
                                                                            "data_group_id"
                                                                        ],
                                                                        "required": true,
                                                                        "columns": [
                                                                            {
                                                                                "title": "数据组",
                                                                                "dataIndex": "name",
                                                                                "key": "name",
                                                                            },
                                                                            {
                                                                                "title": "编号",
                                                                                "dataIndex": "data_group_number",
                                                                                "key": "data_group_number",
                                                                                "search": false
                                                                            }
                                                                        ],
                                                                        "editable": false,
                                                                        "path": "/api/data_group",
                                                                        "extraparams": { is_all: 1 },
                                                                        "rowKey": "id",
                                                                        "rowName": "name",
                                                                        "tabletype": "radio",
                                                                        "disabled": true
                                                                    },
                                                                    "size": {
                                                                        "value": item.size ?? {},
                                                                        "type": "size",
                                                                        "title": "模板展示尺寸",
                                                                        "name": [
                                                                            "size"
                                                                        ],
                                                                        "required": true
                                                                    },
                                                                }
                                                            }
                                                        })
                                                    }} />
                                                </Tooltip>
                                                ,
                                                <Tooltip title="复制">
                                                    <CopyFilled key="copy" onClick={async () => {
                                                        await setdestroy(false);
                                                        setdrawerprops(s => {
                                                            return {
                                                                ...s,
                                                                val: "copy",
                                                                visible: true,
                                                                title: "复制至目标数据组",
                                                                placement: "left",
                                                                width: 450,
                                                                id: item.id,
                                                                fields: {
                                                                    "data_group_id": {
                                                                        "value": [item.data_group_id],
                                                                        "type": "checktable",
                                                                        "title": "选择数据组",
                                                                        "name": [
                                                                            "data_group_id"
                                                                        ],
                                                                        "required": true,
                                                                        "columns": [
                                                                            {
                                                                                "title": "数据组",
                                                                                "dataIndex": "name",
                                                                                "key": "name",
                                                                            },
                                                                            {
                                                                                "title": "编号",
                                                                                "dataIndex": "data_group_number",
                                                                                "key": "data_group_number",
                                                                                "search": false
                                                                            }
                                                                        ],
                                                                        "editable": false,
                                                                        "path": "/api/data_group",
                                                                        "extraparams": { is_all: 1 },
                                                                        "rowKey": "id",
                                                                        "rowName": "name",
                                                                        "tabletype": "radio",
                                                                    }
                                                                }
                                                            }
                                                        })




                                                    }} />
                                                </Tooltip>
                                                ,
                                                <Popconfirm placement="bottom" title={"是否删除？"} onConfirm={() => {
                                                    action.run({ url: "/api/template/" + item.id, params: {}, method: "DELETE" })
                                                }} okText="删除" cancelText="取消">
                                                    <Tooltip title="删除">
                                                        <DeleteFilled key="delete" />
                                                    </Tooltip>
                                                </Popconfirm>
                                                ,
                                            ]}
                                        >
                                            <div style={{ height: 140 }} className='center column' onClick={() => {
                                                history.push({
                                                    pathname: "/list",
                                                    query: {
                                                        name: item.name,
                                                        id: item.id
                                                    }
                                                })
                                            }}>
                                                <div className='imgbg' style={{ marginTop: 8, width: 120, height: 90, backgroundImage: `url(${item.poster ?? require("@/assets/xsl.png")})`, backgroundSize: "contain" }}>

                                                </div>
                                                <p title={item.name} className='oneline' style={{ color: "#1dac57", marginBottom: 0, textAlign: "center" }}>
                                                    {item.name}
                                                </p>
                                                <span style={{ color: "#999", fontSize: 12 }}>
                                                    {typelister[item.size.type]}
                                                </span>
                                            </div>
                                        </Card>

                                    </Col>
                                })
                            }
                        </Row>



                    </TabPane>)
                }

            </Tabs>


        </div>




    </div>);
}

export default Mytemplate;